package com.qtyx.nms.util

import android.animation.Animator
import android.animation.ObjectAnimator
import android.view.View
import android.widget.ImageView
import com.qtyx.nms.R

/**
 * 首页动画
 */
object HomePageAnimUtil {

    /**菜单开关布局**/
    lateinit var menuSwitchLayout:View
    /**菜单开关图标**/
    lateinit var menuSwitchImageView:ImageView
    /**菜单布局**/
    lateinit var menuView:View

    /**动画时间**/
    var duration=400L


    private lateinit var animTranslationY:ObjectAnimator

    /**
     * 菜单开关
     *
     * 打开：开关上移，菜单旋转出来
     *
     * 关闭：菜单旋转出去，开关下移
     */
    fun menuIsOpenMenu(isOpenMenu: Boolean){
        //开关平移距离
        val distanceY =if(isOpenMenu) -30f else  0f
        animTranslationY = ObjectAnimator.ofFloat(menuSwitchLayout, "translationY", DisplayUtil.dp2px(distanceY).toFloat())
        animTranslationY.duration = duration

        if(isOpenMenu){
            animTranslationY.start()
            animTranslationY.addListener(object : Animator.AnimatorListener {
                override fun onAnimationEnd(animation: Animator?) {
                    menuSwitchImageView.setImageResource(R.drawable.ic_menu_switch_on)
                    menuView.visibility=View.VISIBLE
                    menuLayoutAnimation(isOpenMenu)
                }
                override fun onAnimationRepeat(animation: Animator?) {}
                override fun onAnimationCancel(animation: Animator?) {}
                override fun onAnimationStart(animation: Animator?) {}
            })

        }else{
            menuLayoutAnimation(isOpenMenu)
        }
    }

    /**
     * 菜单布局动画
     */
    private fun menuLayoutAnimation(isOpenMenu: Boolean){
        menuView.pivotX=menuView.width/2f
        menuView.pivotY=menuView.height.toFloat()- DisplayUtil.dp2px(18f)

        //旋转角度
        val degrees=if(isOpenMenu) 0f else -180f

        val animRotation = ObjectAnimator.ofFloat(menuView, "rotation", degrees)
        animRotation.duration = duration
        animRotation.start()

        //关闭：菜单旋转出去，开关下移
        if(!isOpenMenu){
            animRotation.addListener(object : Animator.AnimatorListener{
                override fun onAnimationEnd(animation: Animator?) {
                    menuSwitchImageView.setImageResource(R.drawable.ic_menu_switch_off)
                    animTranslationY.start()
                }
                override fun onAnimationRepeat(animation: Animator?) {}
                override fun onAnimationCancel(animation: Animator?) {}
                override fun onAnimationStart(animation: Animator?) {}
            })
        }

    }


}